# -*- coding: utf-8 -*-
__author__ = 'vladbranzei'


import logging
from cherrypy import response
from cherrypy import HTTPError
from onlineutils.web import jsonify, validate, has_scope
from hermes.mapper.inbox_mapper import InboxMapper
from freya.mapper.player_mapper import PlayerMapper


class Hermes(object):

    @jsonify
    @validate
    @has_scope("message")
    def send_message(self, *kwargs):
        args = kwargs[0]

        try:
            token = args['token']
            tokens = token.split("|")
            game = tokens[3]

            credentials = args['credentials']
            t_credentials = tokens[3]
            if credentials == t_credentials:
                response.status = 400
                return "Cannot send message to yourself"
            message = args['message']
            mapper = PlayerMapper()

            if mapper.check(credentials, game) == True:
                vid = mapper.foundUser.vid
                msg_mapper = InboxMapper()
                msg_mapper.create(vid, game, credentials, message)
            else:
                response.status = 404
                return "No user found"

        except KeyError as e:
            response.status = 400
            logging.exception(str(e))
            return "Missing arguments. exception: " + str(e)
        except HTTPError as e:
            response.status = e.args[0]
            logging.exception(str(e))
            return str(e)
        except Exception as e:
            response.status = 500
            logging.exception(str(e))
            return str(e)

    @jsonify
    @validate
    @has_scope("message")
    def get_messages(self, *kwargs):
        args = kwargs[0]

        try:
            game = args['game']
            token = args['token']
            vid = token.split("|")[0]

            mapper = InboxMapper()
            result = mapper.get_messages(vid, game)
            return result

        except KeyError as e:
            response.status = 400
            return e.args[1]
        except HTTPError as e:
            response.status = e.args[0]
            return e.args[1]
        except Exception as e:
            response.status = 500
            logging.exception(str(e))

        return True